package com.sunyifeng.ch05;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class ShapeCache {

    // 缓存
    private static Hashtable<String, Shape> shapeMap = new Hashtable<>();

    public static Shape getShape(String shapeId) {
        Shape cachedShape = shapeMap.get(shapeId);
        // clone方法
        return (Shape) cachedShape.clone();
    }

    // 对每种形状都运行数据库查询，并创建该形状
    // shapeMap.put(shapeKey, shape);
    // 例如，我们要添加三种形状
    public static void loadCache() {
        Circle circle = new Circle();
        circle.setId("1");
        shapeMap.put(circle.getId(),circle);

        Square square = new Square();
        square.setId("2");
        shapeMap.put(square.getId(),square);

        Rectangle rectangle = new Rectangle();
        rectangle.setId("3");
        shapeMap.put(rectangle.getId(),rectangle);

        // 1.for each
//        for(Map.Entry<String, Shape> entry: shapeMap.entrySet()) {
//            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//        }

        // 2.iterator
//        Iterator<Map.Entry<String, Shape>> entries = shapeMap.entrySet().iterator();
//        while (entries.hasNext()) {
//            Map.Entry<String, Shape>  entry = entries.next();
//            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//        }

        // 3.lambda
//        shapeMap.forEach((k, v) -> {
//            System.out.println("K = " + k + ", V = " +v);
//        });

        // 4.stream
        shapeMap.entrySet().stream().forEach((entry -> {
            System.out.println("Stream, K = " + entry.getKey() + "V = " + entry.getValue());
        })) ;

    }
}
